from exporters.exporter import *
from sheetReader import *

class LuaValueExporter:
	def Export(value):
		return value


class LuaIntExporter(LuaValueExporter):
	def Export(value):
		return str(int(float(value)))

class LuaFloatExporter(LuaValueExporter):
	def Export(value):
		return str(float(value))

class LuaStringExporter(LuaValueExporter):
	def Export(value):
		return "\"" + value + "\""


class LuaExporter(Exporter):
	def Export(self, sheet):
		sb = []
		sb.append("---\n--- Created by LuaExporter.\n---\n\n")
		sb.append("---@class " + sheet._name + "\n")
		sb.append("local "+ sheet._name + " = {}\n")

		configMap = sheet.GetConfigMap()
		self.ExportMap(sb, sheet._name, configMap)

		sb.append("\nreturn " + sheet._name)
		return "".join(sb)		


	def ExportMap(self, sb, prefix, configMap):
		listKey = list(configMap.keys())
		keyCount = len(listKey)
		for i in range(0, keyCount):
			key = listKey[i]
			config = configMap[key]
			if (type(config) == dict):
				newPrefix = prefix + "[" + self.ExportValue(key.value, key.valueType) + "]"
				subConfig = config[list(config.keys())[0]]
				if (type(subConfig) == dict):
					sb.append(newPrefix + " = {}\n")
				else:
					sb.append(newPrefix + " = ")
				# sb.append(newPrefix)
				self.ExportMap(sb, newPrefix, config)	
			else:
				if (i == 0):
					sb.append("{")
				sb.append(key + " = " + self.ExportValue(config.value, config.valueType))
				if (i < keyCount - 1):
					sb.append(", ")
				if (i == keyCount - 1):
					sb.append("}\n")


	def ExportValue(self, value, valueType):
		if (valueType == ValueType.SrcValue):
			return LuaValueExporter.Export(value)
		if (valueType == ValueType.IntValue):
			return LuaIntExporter.Export(value)
		if (valueType == ValueType.FloatValue):
			return LuaFloatExporter.Export(value)
		if (valueType == ValueType.StringValue):
			return LuaStringExporter.Export(value)